#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/errno.h>
#define MSGLEN 128
#define RECLAIM_INTERVAL 15

void narrate(char * msg1, char * msg2, struct sockaddr_in * clientp);
void handle_request(char * req, struct sockaddr_in * client, socklen_t addlen);
void _shutdown();
void free_all_tickets();
int setup(char (* _PZarr)[12], int _maxCnt, int * _MaxUsers);

int main(int argc, char * argv[]){
	int cnt = 0;
	FILE * fp = fopen("pz.txt", "r+");
	if (fp == NULL) {
		printf("pz.txt can't open!\n");
		return 0;
	}
	char arr[100][12];
	int cntarr[100];
	while (fscanf(fp, "%d %s", cntarr+cnt, arr[cnt]) > 0) {
		cnt++;
	}
	fclose(fp);
    struct sockaddr_in client_addr;
    socklen_t addrlen = sizeof(client_addr);
    char buf[MSGLEN];
    int ret;
    int sock;
    void ticket_reclaim();
    unsigned time_left;
    sock = setup(arr, cnt, cntarr);
    signal(SIGALRM, ticket_reclaim);
    alarm(RECLAIM_INTERVAL);
    
    while (1){
        addrlen = sizeof(client_addr);
        ret = recvfrom(sock, buf, MSGLEN, 0, (struct sockaddr*)&client_addr, &addrlen);
        if (ret != -1){
            buf[ret] = '\0';
            printf("%s\n", buf);
            narrate("GOT:", buf, &client_addr);
            time_left = alarm(0);
            handle_request(buf, &client_addr, addrlen);
            alarm(time_left);
        }else if (errno != EINTR)
            perror("recvfrom");
    }
}
